import { ref } from "vue";

export default function useTestHooks() {
  const boradcast = ref(null);
  // 初始化广播
  const initBroadcast = () => {

    boradcast.value && destroyBroadcast()
    console.log("初始化 initBroadcast");
    boradcast.value = new BroadcastChannel("test");
    boradcast.value.onmessage = (e) => {
      console.log("onmessage 监听到消息", e);
    }
  };
  // 发送消息
  const sendMessage = (message) => {
    console.log("sendMessage 发送消息", message);
    boradcast.value.postMessage(message);
  }
  // 销毁广播
  const destroyBroadcast = () => {
    console.log("destroyBroadcast 销毁广播");
    boradcast.value && boradcast.value.close();
  }
  return {
    boradcast,
    initBroadcast,
    sendMessage,
    destroyBroadcast
  }
}
